﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Powerpi.Models;
using Powerpi.Services;

namespace Powerpi.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly IMeterService _meterService;
        public HomeController(ILogger<HomeController> logger,IMeterService meterService, IWebHostEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
            _logger = logger;
            _meterService = meterService;
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            //HttpContext.Request.Protocol.
            if (HttpContext.User?.Identity?.IsAuthenticated != true)
            {
                context.Result = new RedirectToActionResult("Index", "Account",
                    new { returnUrl = Uri.EscapeDataString(Request.GetDisplayUrl()) });
                //new RedirectResult($"/account/login?returnUrl={Uri.EscapeDataString(Request.GetDisplayUrl())}");

                return;
            }
            base.OnActionExecuting(context);
        }
        public IActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public IActionResult CallReadMeter()
        {
            _meterService.ReadMeters();
            return Json(Ok());
        }

        public IActionResult Privacy()
        {
            return View();
        }
        public IActionResult Voice()
        {
            var files = System.IO.Directory.GetFiles(System.IO.Path.Combine(Environment.CurrentDirectory, "audio"));
            return View(files);
        }
        [HttpGet]
        public IActionResult Wlan()
        {
            var pwlan = System.IO.Path.Combine(Environment.CurrentDirectory, "wlan");
            if (!Directory.Exists(pwlan))
            {
                Directory.CreateDirectory(pwlan);
                System.IO.File.WriteAllLines(System.IO.Path.Combine(pwlan, "wlan0"), new string[] { "", "", "wpa-ssid ", "wpa-psk " });
            }
            var file = System.IO.File.ReadAllLines(System.IO.Path.Combine(pwlan, "wlan0"));
            var model = new WifiViewModel { SSID = file[2].Split(' ')[1], PSK = file[3].Split(' ')[1] };
            return View(model);

        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Wlan(WifiViewModel model)
        {
            if (ModelState.IsValid)
            {
                System.IO.File.WriteAllLines(System.IO.Path.Combine(Environment.CurrentDirectory, "wlan", "wlan0"),
                    new string[] { "auto wlan0 ", "iface wlan0 inet dhcp ", $"wpa-ssid {model.SSID}", $"wpa-psk {model.PSK}" });
                ViewBag.Message = "保存成功,重启设备生效";
            }
            else
            {
                foreach (var item in ModelState.Values)
                {
                    if (item.Errors.Count > 0)
                    {
                        ModelState.AddModelError("", item.Errors[0].ErrorMessage);
                        ViewBag.Message = item.Errors[0].ErrorMessage;
                    }
                }

            }
            return View(model);
        }
        [HttpGet]
        public IActionResult Device()
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile($"appsettings.{_hostingEnvironment.EnvironmentName}.json", true, reloadOnChange: true);

            var config = builder.Build();
            DeviceViewModel model = new DeviceViewModel
            {
                DeviceId = config["appSettings:DeviceId"],
                Secret = config["appSettings:DeviceSecret"]
            };

            return View(model);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Device(DeviceViewModel model)
        {
            if (ModelState.IsValid)
            {
                var filePath = Path.Combine(Environment.CurrentDirectory, $"appsettings.{_hostingEnvironment.EnvironmentName}.json");
                JObject jsonObject;
                using (StreamReader file = new StreamReader(filePath))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jsonObject = (JObject)JToken.ReadFrom(reader);
                    jsonObject["AppSettings"]["DeviceId"] = model.DeviceId;
                    jsonObject["AppSettings"]["DeviceSecret"] = model.Secret;
                }

                using (var writer = new StreamWriter(filePath))
                using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
                {
                    jsonObject.WriteTo(jsonwriter);
                }

                ViewBag.Message = "保存成功,重启设备生效";
            }
            else
            {
                foreach (var item in ModelState.Values)
                {
                    if (item.Errors.Count > 0)
                    {
                        ModelState.AddModelError("", item.Errors[0].ErrorMessage);
                        ViewBag.Message = item.Errors[0].ErrorMessage;
                    }
                }

            }
            return View(model);
        }
        [HttpGet]
        public IActionResult Meter()
        {
            var pwlan = System.IO.Path.Combine(Environment.CurrentDirectory, "Files");
            if (!Directory.Exists(pwlan))
            {
                Directory.CreateDirectory(pwlan);
                System.IO.File.WriteAllText(System.IO.Path.Combine(pwlan, "meters"), "");
            }
            var file = System.IO.File.ReadAllText(System.IO.Path.Combine(pwlan, "meters"));
            ViewBag.Meters = file;
            return View();

        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Meter(string meters)
        {
            if (ModelState.IsValid)
            {

                System.IO.File.WriteAllLines(System.IO.Path.Combine(Environment.CurrentDirectory, "Files", "meters"),
                    meters.Split(new char[] { ',', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries));
                ViewBag.Message = "保存成功";
            }
            else
            {
                foreach (var item in ModelState.Values)
                {
                    if (item.Errors.Count > 0)
                    {
                        ModelState.AddModelError("", item.Errors[0].ErrorMessage);
                        ViewBag.Message = item.Errors[0].ErrorMessage;
                    }
                }

            }
            ViewBag.Meters = meters;

            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
